<template>
	<view>
		<canvas type="2d" id="myCanvas" canvas-id="myCanvas"></canvas>
		<view @click="save" class="btn-save">保存图片</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				path: '',
				detail: {},
				count: 0, //图片加载计数
				clicked: false, //点击了保存
				canvas: null,
				canvasWidth: 325, //352px
			}
		},
		onLoad: function(options) {

			this.detail = JSON.parse(options.detail)
			console.log(this.detail)
			if (this.detail) {
				this.getHouseSharePoster();

				// this.draw();
			}

		},

		methods: {
			//获取小程序码
			getHouseSharePoster() {
				this.$api.getHouseSharePoster(this.detail.id).then(res => {
					let data = res.data.data;
					this.path = data;
					//声明系统文件
					// let fs = wx.getFileSystemManager();
					// let times = new Date().getTime();
					// let codeImg = wx.env.USER_DATA_PATH + '/' + times + '.jpg';
					// //写入图片
					// fs.writeFile({
					// 	filePath: codeImg,
					// 	data: data.slice(22),
					// 	encoding: 'base64',
					// 	success: () => {
					// 		this.setData({
					// 			path: codeImg
					// 		})
					// 		console.log('111', this.data.path);
					// 		this.draw();

					// 	}
					// })
					this.draw();

				})
			},

			draw() {
				console.log('111111')
				const ctx = uni.createCanvasContext('myCanvas');
				ctx.fillStyle = "#ffffff";
				ctx.fillRect(0, 0, this.canvasWidth, 480);
				//绘制banner
				console.log('2222')

				const drawBanner = (src, startX, startY, width, height) => {
					uni.downloadFile({
						url: src,
						success: (res) => {
							console.log('图片', res);
							ctx.drawImage(res.tempFilePath, startX, startY, width, height);
							this.count++;
							if (this.count == 3) {
								ctx.draw(true);
								if (this.clicked == true) {
									uni.hideLoading();
									this.save();
								}
							}

							// if (this.count == 3 && this.clicked == true) {
							// 	wx.hideLoading();
							// 	this.save();
							// }
						}
					})
				}

				console.log(this.detail.images)
				drawBanner(this.detail.images[0], 15, 15, 145, 180);
				drawBanner(this.detail.images[1], 165, 15, 145, 87);
				drawBanner(this.detail.images[2], 165, 107, 145, 87);


				ctx.font = "bold 16px MicrosoftYaHei-Bold";
				ctx.fillStyle = "#333333";
				var str = this.detail.title;
				var lineWidth = 0;
				var canvasWidth = this.canvasWidth - 30; //计算canvas的宽度
				var initHeight = 220; //绘制字体距离canvas顶部初始的高度
				var lastSubStrIndex = 0; //每次开始截取的字符串的索引
				for (let i = 0; i < str.length; i++) {
					lineWidth += ctx.measureText(str[i]).width;
					if (lineWidth > canvasWidth) {
						ctx.fillText(str.substring(lastSubStrIndex, i), 15, initHeight); //绘制截取部分
						initHeight += 25; //20为字体的高度
						lineWidth = 0;
						lastSubStrIndex = i;
					}
					if (i == str.length - 1) { //绘制剩余部分
						ctx.fillText(str.substring(lastSubStrIndex, i + 1), 15, initHeight);
					}

				}


				ctx.font = "11px MicrosoftYaHei";
				console.log(this.detail.tbHouse.posterDescribe)
				ctx.fillText(this.detail.tbHouse.posterDescribe, 15, 270);
				// 绘制标签
				var arrlable = [this.detail.tbHouse.houseArea + 'm²', this.detail.tbHouse.houseType || '',
					this.detail.tbHouse.decorate, this.detail.tbHouse.type, this.detail
					.tbHouse.age + '年'
				];

				// var arrlable = ['107m²', '5555','55555', '记者女皇', '2015年'
				// ];
				//初始左边位置
				let left = 15;
				arrlable.forEach(drawLabel)

				function drawLabel(text) {
					//获取文字宽度
					const metrics = ctx.measureText(text)
					//文字据左右两边的距离
					let padding = 6
					//每个块的宽度
					let itemWidth = metrics.width + padding * 2
					ctx.beginPath()
					//画背景
					ctx.fillStyle = '#EEEEFE';
					ctx.fillRect(left, 285, itemWidth, 20)
					//画文字
					ctx.fillStyle = '#585CF7'
					ctx.fillText(text, left + padding, 300)
					ctx.closePath()
					// +5是两个块之间的间距
					left += itemWidth + 5
				}

				/**
				 * 绘制文字
				 * @param {*} font 字体样式
				 * @param {*} fillStyle 字体颜色
				 * @param {*} content 内容
				 * @param {*} startX 开始位置x
				 * @param {*} startY 开始位置y
				 */
				const drawText = (font, fillStyle, content, startX, startY) => {
					ctx.font = font;
					ctx.fillStyle = fillStyle;
					ctx.fillText(content, startX, startY);
					return ctx.measureText(content).width
				}

				let textWidth = 0
				//起拍价
				textWidth = drawText("bold 19px PingFang-SC-Heavy", '#FC4073', this.detail.tbHouse.origin,
					15, 337)
				//起拍价单位
				drawText("12px PingFang-SC-Heavy", '#FC4073', '万', textWidth + 17, 337)
				drawText("12px PingFang-SC-Heavy", '#333333', '起拍价', 15, 357)
				drawText("10px PingFang-SC-Heavy", '#999999', '（起拍时间：' + this.detail.tbHouse.auctionTime +
					'）', 52, 357)

				// 市场价
				ctx.fillStyle = "#999999";
				ctx.font = "12px PingFang-SC-Heavy";
				textWidth = ctx.measureText('万').width;
				var textX = this.canvasWidth - textWidth - 15;
				ctx.fillText('万', textX, 337);


				ctx.font = "19px PingFang-SC-Heavy";
				var priWidth = ctx.measureText(this.detail.tbHouse.housePrice).width;
				var prX = this.canvasWidth - 15 - textWidth - priWidth - 5;
				ctx.fillText(this.detail.tbHouse.housePrice, prX, 337)
				//绘制中划线
				ctx.moveTo(prX, 330); //设置线条的起始路径坐标
				ctx.lineTo(textX, 332); //设置线条的终点路径坐标
				ctx.lineWidth = '3';
				ctx.strokeStyle = "#999999";
				ctx.stroke(); //对当前路径进行描边
				ctx.font = "11px PingFang-SC-Heavy";
				var scjWidth = ctx.measureText('市场价').width;
				var scjX = prX + (priWidth + textWidth) / 2 - (scjWidth / 2); //价格的X+ （价格的宽+单位的宽）/2-（自身的宽/2） 
				ctx.fillText('市场价', scjX, 357);

				//分割线
				ctx.beginPath();
				ctx.arc(-5, 390, 15, 0, Math.PI * 2, 1);
				ctx.closePath();
				ctx.fillStyle = '#F5F5F5';
				ctx.lineWidth = 1;
				ctx.fill();

				ctx.beginPath();
				ctx.arc(this.canvasWidth + 5, 390, 15, 0, Math.PI * 2, 1);
				ctx.closePath();
				ctx.fillStyle = '#F5F5F5';
				ctx.fill();

				ctx.beginPath();
				ctx.setLineDash([5, 10], 5);
				ctx.moveTo(25, 390); //设置线条的起始路径坐标
				ctx.lineTo(this.canvasWidth - 25, 390); //设置线条的终点路径坐标
				ctx.closePath();
				ctx.strokeStyle = "#DDDDDD";
				ctx.stroke(); //对当前路径进行描边

				// 小程序码
				// uni.downloadFile({
				// 	url: this.path,
				// 	success: (res) => {
				// 		console.log(res);
				// 		ctx.drawImage(res.tempFilePath, 15, 405, 60, 60);

				// 	}
				// })

				// 扫码文案
				drawText("15px PingFang-SC-Medium", "#333333", '扫码查看更多优质房源', 95, 430)
				drawText("12px PingFang-SC-Medium", "#999999", '专业团队配合房源尽调，法拍房零风险', 95, 455)
				setTimeout(()=>{
					ctx.drawImage(this.path, 15, 405, 60, 60);
					ctx.draw(true);
				},0)
			},


			save() {
				this.clicked = true;
				console.log('点击保存')
				if (this.count == 3) {
					console.log('图片加载完成')
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						// canvas: this.canvas,
						width: 325,
						height: 480,
						success: (res) => {
							console.log('转换成功')
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success(res) {
									uni.showToast({
										icon: 'none',
										title: '保存成功',
									})
								},
								fail(err) {
									console.log(err)
								},
							})
						},
						fail: function(res) {
							console.log(res);
						}
					});

				} else {
					uni.showLoading({
						title: '海报生成中',
						mask: true
					})
				}
			},
		},
	}
</script>

<style>
	page {
		background-color: #f8f8f8;
		padding: 50rpx 0 0;
		box-sizing: border-box;
	}

	#myCanvas {
		width: 325px;
		height: 480px;
		background-color: #FFFFFF;
		margin: 0 auto;
		/* display: none; */
	}

	.btn-save {
		width: 650rpx;
		height: 98rpx;
		background: #585CF7;
		border-radius: 49rpx;
		text-align: center;
		line-height: 98rpx;
		margin: 70rpx auto 0;
		font-size: 36rpx;
		color: #FFFFFF;
	}

	.img-can {
		width: 650rpx;
		height: 960rpx;
		margin: 0 auto;
		display: block;

	}
</style>
